package com.example.app.yidu.activity.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.app.yidu.R;
import com.example.app.yidu.activity.NewsActivity;
import com.example.app.yidu.activity.adapter.SimpleAdapter;
import com.example.app.yidu.activity.adapter.TjFragmentViewPagerAdapter;
import com.example.app.yidu.activity.bean.Cnode;
import com.example.app.yidu.activity.utils.ToastUtil;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/12/14.
 */

public class TjFragment extends Fragment {
    private LayoutInflater inflater;
    private int yeshu=1;
    private SwipeRefreshLayout srfl;
    private RecyclerView tj_rlv;
    private View view;
    private Toolbar toolbar;
    private LinearLayout fgm_ll;
    private ViewPager fgm_tj_vp;
    private List<ImageView> list=new ArrayList<>();
    private List<String[]> cnodeList=new ArrayList<>();
    private int preposition,newposition;
    private SimpleAdapter sa;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.fragment_tj,null);
        initView();
        initData();
        getAdapter();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        inflater=LayoutInflater.from(getContext());
        toolbar= (Toolbar) getActivity().findViewById(R.id.toolbar);
        toolbar.setTitle("推荐");
        toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        toolbar.setLogo(R.mipmap.ic_launcher);
        RefreshListener listener=new RefreshListener();
        srfl.setOnRefreshListener(listener);
        //首次进入手动调用，此方法相当于手动下拉刷新，调用onRefresh（）。
        listener.onRefresh();
        sa.setItemClickListener(new SimpleAdapter.MyItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent=new Intent(getActivity(), NewsActivity.class);
                intent.putExtra("url","https://cnodejs.org/topic/"+cnodeList.get(position)[2]);
                startActivity(intent);
            }
        });
    }
    /**
     * 数据初始化显示
     */
    private void initData() {
        OkHttpClient oc=new OkHttpClient();
        Request request=new Request.Builder().url("https://cnodejs.org/api/v1/topics?page="+yeshu).build();
        oc.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.toast(getContext(),"网络异常！");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String info=response.body().string();
                Gson gson=new Gson();
                Cnode cnode=gson.fromJson(info,Cnode.class);
                List<Cnode.DataBean> list=cnode.getData();
                for (int a=0;a<list.size();a++) {
                    String title=list.get(a).getTitle();//标题
                    String url=list.get(a).getId();//得到网址所需的id
                    String icon=list.get(a).getAuthor().getAvatar_url();//头像
                    String lastpush=list.get(a).getLast_reply_at();//最后一次提交时间
                    String replycount=list.get(a).getReply_count()+"";//回复数量
                    String visitcount=list.get(a).getVisit_count()+"";//访问数量
                    String[] arr=new String[]{
                      title,icon,url,lastpush,replycount,visitcount
                    };
//                    cnodeList.add(arr);
                    cnodeList.add(0,arr);
                }
            }
        });

    }

    /**
     * 设置适配器
     */
    private void getAdapter() {
        sa=new SimpleAdapter(getActivity(),cnodeList);
        tj_rlv.setAdapter(sa);
        LinearLayoutManager lm=new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL,false);
        tj_rlv.setLayoutManager(lm);
    }

    /**
     * 初始化view
     */
    private void initView() {
        fgm_ll= (LinearLayout) view.findViewById(R.id.fgm_ll);
        fgm_tj_vp= (ViewPager) view.findViewById(R.id.fgm_tj_vp);
        initDat();
        TjFragmentViewPagerAdapter tva=new TjFragmentViewPagerAdapter(list,fgm_tj_vp);
        fgm_tj_vp.setAdapter(tva);
        //设置在初始化时候，选中第0个view点为白色，在这之前initDt之中把所有置为灰色
        fgm_ll.getChildAt(0).setEnabled(true);
        //设置viewpager滑动监听
        fgm_tj_vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                newposition=position%list.size();
                fgm_ll.getChildAt(preposition).setEnabled(false);
                fgm_ll.getChildAt(newposition).setEnabled(true);
                preposition=newposition;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //初始化时候，把viewpager首页放在整数最大值的中间，因为涉及余数，所以减去余数。
        int m=(Integer.MAX_VALUE/2)%list.size();
        fgm_tj_vp.setCurrentItem((Integer.MAX_VALUE/2)-m);
        //得到首页下半部分id.
        srfl= (SwipeRefreshLayout) view.findViewById(R.id.tj_srfl);
        tj_rlv= (RecyclerView) view.findViewById(R.id.tj_rlv);
    }

    private void initDat() {
        int[] resIds={
                R.drawable.a,
                R.drawable.b,
                R.drawable.c,
                R.drawable.d
        };
        ImageView iv;
        View view;
        for (int a=0;a<resIds.length;a++) {
            iv=new ImageView(getActivity());
            iv.setBackgroundResource(resIds[a]);
            list.add(iv);
            //创建view对象
            view=new View(getActivity());
            //参数是宽高
            LinearLayout.LayoutParams pars=new LinearLayout.LayoutParams(10,10);
            //除了第一个小圆点之外，全部距左边20
            if (a!=0) {
                pars.leftMargin=20;
            }
            view.setLayoutParams(pars);
            view.setBackgroundResource(R.drawable.point);
            //初始化时候最先在此处设置小圆点状态，都设置成灰色
            view.setEnabled(false);
            fgm_ll.addView(view);
        }
    }


    private class RefreshListener implements SwipeRefreshLayout.OnRefreshListener {
        @Override
        public void onRefresh() {
            new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //让刷新动画隐藏
                        srfl.setRefreshing(false);
                        yeshu++;//页数自加，从而相应刷新数据操作
                        initData();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                sa.notifyDataSetChanged();
                            }
                        });
                    }
                },2000);
        }
    }
}
